#include "xfileutils.h"
#include <map>
#include <Windows.h>

// record the resource path
static char g_resourcePath[MAX_PATH] = {0};
static std::map<std::string, std::string> g_fullPathCache;

static void _checkPath()
{
    if (!g_resourcePath[0])
    {
        WCHAR  path[MAX_PATH] = {0};
        int nNum = ::WideCharToMultiByte(CP_ACP, 0, path,
            ::GetCurrentDirectoryW(sizeof(path), path),
            g_resourcePath, MAX_PATH, NULL, NULL);
        g_resourcePath[nNum] = '\\';
    }
}

static xFileUtils *g_fileUtils = NULL;

xFileUtils *xFileUtils::sharedFiltUtils()
{
    if (g_fileUtils == NULL)
    {
        _checkPath();
        g_fileUtils = new xFileUtils;
        g_fileUtils->init();
    }
    
    return g_fileUtils;
}

std::string xFileUtils::fullPathForFileName(const char *fileName)
{
    // Return directly if it's an absolute path
    if (strlen(fileName) > 3 
        && ((fileName[0] >= 'a' && fileName[0] <= 'z') || (fileName[0] >= 'A' && fileName[0] <= 'Z'))
        && (fileName[1] == ':')
        && (fileName[2] == '\\' || fileName[2] == '/'))
    {
        return fileName;
    }

    // Is already cached?
    std::map<std::string, std::string>::iterator cacheIter = g_fullPathCache.find(fileName);
    if (cacheIter != g_fullPathCache.end())
    {
        return cacheIter->second;
    }

    std::string newFileName = getNewFileName(fileName);

}

bool xFileUtils::init()
{
    _defaultResRootPath = g_resourcePath;
    _searchPathArray.push_back(_defaultResRootPath);

    return true;
}

std::string xFileUtils::getNewFileName(const char *fileName)
{
    const char *newFileName = NULL;
    // in Lookup FileName dictionary?
    // xString *fileNameFound = 
    return " ";
}